<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"littlefxc.github.io","root":"/","images":"/images","scheme":"Mist","version":"8.2.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":false,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>
<meta name="description" content="1 前言池化技术是性能调优的重要措施，池化的思想是把对象放到池子里面，当要使用的时候从池子里面拿对象，用完之后在放回池子里面。这样可以降低资源分配和释放资源的开销，从而提升性能。">
<meta property="og:type" content="article">
<meta property="og:title" content="对象池 commons-pool2">
<meta property="og:url" content="http://littlefxc.github.io/2021/08/01/%E5%AF%B9%E8%B1%A1%E6%B1%A0-commons-pool2/index.html">
<meta property="og:site_name" content="一年春又来">
<meta property="og:description" content="1 前言池化技术是性能调优的重要措施，池化的思想是把对象放到池子里面，当要使用的时候从池子里面拿对象，用完之后在放回池子里面。这样可以降低资源分配和释放资源的开销，从而提升性能。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801162749626.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801162852280.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801211018346.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801211157285.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801211531498.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801211544503.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801212906811.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801212937024.png">
<meta property="og:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801213320219.png">
<meta property="article:published_time" content="2021-08-01T05:48:21.000Z">
<meta property="article:modified_time" content="2021-08-01T13:58:31.657Z">
<meta property="article:author" content="一年春又来">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="池化技术">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801162749626.png">


<link rel="canonical" href="http://littlefxc.github.io/2021/08/01/%E5%AF%B9%E8%B1%A1%E6%B1%A0-commons-pool2/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>
<title>对象池 commons-pool2 | 一年春又来</title>
  




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="一年春又来" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">一年春又来</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="home                          //首页 fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="archive          //归档 fa-fw"></i>归档</a></li>
        <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="th           //分类 fa-fw"></i>分类</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="tags                     //标签 fa-fw"></i>标签</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-%E5%89%8D%E8%A8%80"><span class="nav-text">1 前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-%E5%AF%B9%E8%B1%A1%E6%B1%A0-%E9%80%82%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="nav-text">2 对象池 - 适用场景</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-commons-pool2"><span class="nav-text">3 commons-pool2</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-ObjectPool-%E6%8E%A5%E5%8F%A3"><span class="nav-text">3.1 ObjectPool 接口</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-1-%E5%AE%9E%E7%8E%B0%E7%B1%BB%E4%BB%8B%E7%BB%8D"><span class="nav-text">3.1.1 实现类介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-2-%E6%A0%B8%E5%BF%83API"><span class="nav-text">3.1.2 核心API</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-KeyedObjectPool"><span class="nav-text">3.2 KeyedObjectPool</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-1-PooledObjectFactory"><span class="nav-text">3.2.1 PooledObjectFactory</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-2-PooledObjectFactory-%E6%A0%B8%E5%BF%83API"><span class="nav-text">3.2.2 PooledObjectFactory 核心API</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-3-PooledObject"><span class="nav-text">3.2.3 PooledObject</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-2-%E7%A4%BA%E4%BE%8B%E4%BB%A3%E7%A0%81"><span class="nav-text">3.2.2 示例代码</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-3-commons-pool2-%E5%B0%8F%E7%BB%93"><span class="nav-text">3.3 commons-pool2 小结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-4-commons-pool2-%E9%85%8D%E7%BD%AE"><span class="nav-text">3.4 commons-pool2 配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-1-GenericObjectPoolPoolConfig"><span class="nav-text">3.4.1 GenericObjectPoolPoolConfig</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-2-AbandonedConfig"><span class="nav-text">3.4.2 AbandonedConfig</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-3-%E6%B3%A8%E6%84%8F%E7%82%B9"><span class="nav-text">3.4.3 注意点</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-5-Abandon-%E4%B8%8E-Evict-%E5%8C%BA%E5%88%AB"><span class="nav-text">3.5 Abandon 与 Evict 区别</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">一年春又来</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">203</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">35</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">124</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://littlefxc.github.io/2021/08/01/%E5%AF%B9%E8%B1%A1%E6%B1%A0-commons-pool2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="一年春又来">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="一年春又来">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          对象池 commons-pool2
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2021-08-01 13:48:21 / 修改时间：21:58:31" itemprop="dateCreated datePublished" datetime="2021-08-01T13:48:21+08:00">2021-08-01</time>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="1-前言"><a href="#1-前言" class="headerlink" title="1 前言"></a>1 前言</h1><p>池化技术是性能调优的重要措施，池化的思想是把对象放到池子里面，当要使用的时候从池子里面拿对象，用完之后在放回池子里面。这样可以降低资源分配和释放资源的开销，从而提升性能。</p>
<span id="more"></span>

<p>在实际的项目中，我们每天都会接触到池化技术，例如：</p>
<ul>
<li>对象池：通过复用对象，减少对象创建、垃圾回收的开销</li>
<li>线程池：通过复用线程来提升性能</li>
<li>连接池：如数据库连接池、Redis连接池、HTTP连接池，通过复用TCP连接来减少创建和释放连接的时间来提升性能</li>
</ul>
<h1 id="2-对象池-适用场景"><a href="#2-对象池-适用场景" class="headerlink" title="2 对象池 - 适用场景"></a>2 对象池 - 适用场景</h1><ul>
<li>维护一些很大、创建很慢的的对象来提升性能</li>
<li>缺点：有学习成本、增加了代码复杂度</li>
</ul>
<h1 id="3-commons-pool2"><a href="#3-commons-pool2" class="headerlink" title="3 commons-pool2"></a>3 commons-pool2</h1><ul>
<li>Apache 基金会开源的对象池框架</li>
<li>官网：<a target="_blank" rel="noopener" href="https://commons.apache.org/proper/commons-pool/">https://commons.apache.org/proper/commons-pool/</a></li>
<li>Github：<a target="_blank" rel="noopener" href="https://github.com/apache/commons-pool">https://github.com/apache/commons-pool</a></li>
</ul>
<p>commons-pool2 提供了两种对象池：</p>
<h2 id="3-1-ObjectPool-接口"><a href="#3-1-ObjectPool-接口" class="headerlink" title="3.1 ObjectPool 接口"></a>3.1 ObjectPool 接口</h2><p>ObjectPool 是一个接口</p>
<h3 id="3-1-1-实现类介绍"><a href="#3-1-1-实现类介绍" class="headerlink" title="3.1.1 实现类介绍"></a>3.1.1 实现类介绍</h3><table>
<thead>
<tr>
<th>实现类</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td>BaseObjectPool</td>
<td>抽象类，用来扩展自己的对象池</td>
</tr>
<tr>
<td>ErodingObjectPool</td>
<td>“腐蚀”对象池，代理一个对象池，并基于factor参数，为其添加“腐蚀”行为。归还的对象被腐蚀后，将会丢弃，而不是添加到空闲容量中。</td>
</tr>
<tr>
<td><strong>GenericObjectPool</strong></td>
<td>一个可配置的通用对象池实现</td>
</tr>
<tr>
<td>ProxiedObjectPool</td>
<td>代理一个其它的对象池，并基于动态代理（支持JDK代理和Cglib代理），返回一个代理后的对象。该对象池主要用来增强对池化对象的控制，比如防止在归还该对象后，还继续使用该对象等行为。</td>
</tr>
<tr>
<td>SoftReferenceObjectPool</td>
<td>基于软引用的对象池</td>
</tr>
<tr>
<td>SynchroizedObjectPool</td>
<td>代理一个其它的对象池，并为其提供线程安全的能力</td>
</tr>
</tbody></table>
<h3 id="3-1-2-核心API"><a href="#3-1-2-核心API" class="headerlink" title="3.1.2 核心API"></a>3.1.2 核心API</h3><table>
<thead>
<tr>
<th>方法名</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td>borrowObject()</td>
<td>从对象池借对象</td>
</tr>
<tr>
<td>returnObject()</td>
<td>将对象归还到对象池</td>
</tr>
<tr>
<td>invalidateObject()</td>
<td>失效一个对象</td>
</tr>
<tr>
<td>addObject()</td>
<td>增加一个空闲对象，该方法适用于使用空闲对象预加载对象池</td>
</tr>
<tr>
<td>clear()</td>
<td>清空空闲的所有对象，并释放相关资源</td>
</tr>
<tr>
<td>close()</td>
<td>关闭对象池，并释放相关资源</td>
</tr>
<tr>
<td>getNumIdIe()</td>
<td>获得空闲的对象数量</td>
</tr>
<tr>
<td>getNumActive()</td>
<td>获得被借出对象数量</td>
</tr>
</tbody></table>
<h2 id="3-2-KeyedObjectPool"><a href="#3-2-KeyedObjectPool" class="headerlink" title="3.2 KeyedObjectPool"></a>3.2 KeyedObjectPool</h2><p>它和ObejectPool的区别在于它是通过 Key 来找对象的。从设计上的角度看，KeyedObjectPool 和 ObjectPool 没有多少区别，它有以下实现类：</p>
<table>
<thead>
<tr>
<th>实现类</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td>ErodingKeyedObjectPool</td>
<td>类似ErodingObjectPool</td>
</tr>
<tr>
<td>GenericKeyedObjectPool</td>
<td>类似GenericObjectPool</td>
</tr>
<tr>
<td>ProxiedKeyedObjectPool</td>
<td>类似ProxiedObjectPool</td>
</tr>
<tr>
<td>SynchroizedKeyedObjectPool</td>
<td>类似SynchroizedObjectPool</td>
</tr>
</tbody></table>
<h3 id="3-2-1-PooledObjectFactory"><a href="#3-2-1-PooledObjectFactory" class="headerlink" title="3.2.1 PooledObjectFactory"></a>3.2.1 PooledObjectFactory</h3><table>
<thead>
<tr>
<th>实现类</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td>BasePooledObjectFactory</td>
<td>抽象类，用于扩展自己的PooledObjectFactory</td>
</tr>
<tr>
<td>PoolUtils.SynchronizedPooledObjectFactory</td>
<td>内部类，代理一个其它的PooledObjectFactory，实现线程同步，用 <code>PoolUtils.synchronizedPooledFactory()</code>创建</td>
</tr>
</tbody></table>
<h3 id="3-2-2-PooledObjectFactory-核心API"><a href="#3-2-2-PooledObjectFactory-核心API" class="headerlink" title="3.2.2 PooledObjectFactory 核心API"></a>3.2.2 PooledObjectFactory 核心API</h3><table>
<thead>
<tr>
<th>方案名</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td>makeObject</td>
<td>创建一个对象实例，并将其包装成一个PooledObject</td>
</tr>
<tr>
<td>destroyObject</td>
<td>销毁对象</td>
</tr>
<tr>
<td>validateObject</td>
<td>校验对象，确保对象池返回的对象是OK的</td>
</tr>
<tr>
<td>activeObject</td>
<td>重新初始化对象</td>
</tr>
<tr>
<td>passivated</td>
<td>取消初始化对象。GenriObjectPool 的 addIdIeObject、returnObject、evict调用该方法</td>
</tr>
</tbody></table>
<h3 id="3-2-3-PooledObject"><a href="#3-2-3-PooledObject" class="headerlink" title="3.2.3 PooledObject"></a>3.2.3 PooledObject</h3><table>
<thead>
<tr>
<th>实现类</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td>DefaultPooledObject</td>
<td>包装原始对象，实现监控（例如创建时间、使用时间等）、状态跟踪等</td>
</tr>
<tr>
<td>PooledSoftReferenceObject</td>
<td>进一步封装了DefaultPooledObject，用来和SoftReferenceObjectPool配置使用</td>
</tr>
</tbody></table>
<p><strong>PooledObject状态</strong></p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801162749626.png" alt="image-20210801162749626"></p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801162852280.png" alt="image-20210801162852280"></p>
<h3 id="3-2-2-示例代码"><a href="#3-2-2-示例代码" class="headerlink" title="3.2.2 示例代码"></a>3.2.2 示例代码</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"># 对象</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Money</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Money <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 假设对象new非常耗时</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      Thread.sleep(<span class="number">10L</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Money(<span class="string">&quot;USD&quot;</span>, <span class="keyword">new</span> BigDecimal(<span class="string">&quot;1&quot;</span>));</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">private</span> String type;</span><br><span class="line">  <span class="keyword">private</span> BigDecimal amount;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="title">Money</span><span class="params">(String type, BigDecimal amount)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      Thread.sleep(<span class="number">100L</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">      e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.type = type;</span><br><span class="line">    <span class="keyword">this</span>.amount = amount;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 省略 getter,setter</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 对象池工厂类</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MoneyPooledObjectFactory</span></span></span><br><span class="line"><span class="class">  <span class="keyword">implements</span> <span class="title">PooledObjectFactory</span>&lt;<span class="title">Money</span>&gt; </span>&#123;</span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger LOGGER =</span><br><span class="line">    LoggerFactory.getLogger(MoneyPooledObjectFactory.class);</span><br><span class="line"></span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> PooledObject&lt;Money&gt; <span class="title">makeObject</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    DefaultPooledObject&lt;Money&gt; object = <span class="keyword">new</span> DefaultPooledObject&lt;&gt;(</span><br><span class="line">      <span class="keyword">new</span> Money(<span class="string">&quot;USD&quot;</span>, <span class="keyword">new</span> BigDecimal(<span class="string">&quot;1&quot;</span>))</span><br><span class="line">    );</span><br><span class="line">    LOGGER.info(<span class="string">&quot;makeObject..state = &#123;&#125;&quot;</span>, object.getState());</span><br><span class="line">    <span class="keyword">return</span> object;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">destroyObject</span><span class="params">(PooledObject&lt;Money&gt; p)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    LOGGER.info(<span class="string">&quot;destroyObject..state = &#123;&#125;&quot;</span>, p.getState());</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">validateObject</span><span class="params">(PooledObject&lt;Money&gt; p)</span> </span>&#123;</span><br><span class="line">    LOGGER.info(<span class="string">&quot;validateObject..state = &#123;&#125;&quot;</span>, p.getState());</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">activateObject</span><span class="params">(PooledObject&lt;Money&gt; p)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    LOGGER.info(<span class="string">&quot;activateObject..state = &#123;&#125;&quot;</span>, p.getState());</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">passivateObject</span><span class="params">(PooledObject&lt;Money&gt; p)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    LOGGER.info(<span class="string">&quot;passivateObject..state = &#123;&#125;&quot;</span>, p.getState());</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 测试类</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CommonsPool2Test</span> </span>&#123;</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    GenericObjectPool&lt;Money&gt; pool = <span class="keyword">new</span> GenericObjectPool&lt;&gt;(<span class="keyword">new</span> MoneyPooledObjectFactory());</span><br><span class="line">    Money money = pool.borrowObject();</span><br><span class="line">    money.setType(<span class="string">&quot;RMB&quot;</span>);</span><br><span class="line">    pool.returnObject(money);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"># 测试结果</span><br><span class="line">  </span><br><span class="line">makeObject..state = IDLE</span><br><span class="line">activateObject..state = ALLOCATED</span><br><span class="line">passivateObject..state = RETURNING</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h2 id="3-3-commons-pool2-小结"><a href="#3-3-commons-pool2-小结" class="headerlink" title="3.3 commons-pool2 小结"></a>3.3 commons-pool2 小结</h2><ul>
<li><p>ObjectPool：对象池</p>
<ul>
<li>最核心：GenericObjectPool、GenericKeyedObjectPool</li>
</ul>
</li>
<li><p>Factory：创建和管理 PooledObject</p>
<ul>
<li>一般要自己扩展</li>
</ul>
</li>
<li><p>PooledObject：包装原有的对象，从而让对象池管理</p>
<ul>
<li>一般用 DefaultPooledObject</li>
</ul>
</li>
</ul>
<p>只要掌握这三点，一般就没有问题了</p>
<h2 id="3-4-commons-pool2-配置"><a href="#3-4-commons-pool2-配置" class="headerlink" title="3.4 commons-pool2 配置"></a>3.4 commons-pool2 配置</h2><h3 id="3-4-1-GenericObjectPoolPoolConfig"><a href="#3-4-1-GenericObjectPoolPoolConfig" class="headerlink" title="3.4.1 GenericObjectPoolPoolConfig"></a>3.4.1 GenericObjectPoolPoolConfig</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801211018346.png" alt="image-20210801211018346"></p>
<h3 id="3-4-2-AbandonedConfig"><a href="#3-4-2-AbandonedConfig" class="headerlink" title="3.4.2 AbandonedConfig"></a>3.4.2 AbandonedConfig</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801211157285.png" alt="image-20210801211157285"></p>
<h3 id="3-4-3-注意点"><a href="#3-4-3-注意点" class="headerlink" title="3.4.3 注意点"></a>3.4.3 注意点</h3><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801211531498.png" alt="image-20210801211531498"></p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801211544503.png" alt="image-20210801211544503"></p>
<h2 id="3-5-Abandon-与-Evict-区别"><a href="#3-5-Abandon-与-Evict-区别" class="headerlink" title="3.5 Abandon 与 Evict 区别"></a>3.5 Abandon 与 Evict 区别</h2><p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801212906811.png" alt="image-20210801212906811"></p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801212937024.png" alt="image-20210801212937024"></p>
<p><img src="https://gitee.com/littlefxc/oss/raw/master/images/image-20210801213320219.png" alt="image-20210801213320219"></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Java/" rel="tag"># Java</a>
              <a href="/tags/%E6%B1%A0%E5%8C%96%E6%8A%80%E6%9C%AF/" rel="tag"># 池化技术</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/07/27/%E9%93%BE%E8%B7%AF%E8%BF%BD%E8%B8%AAzipkin/" rel="prev" title="链路追踪zipkin">
                  <i class="fa fa-chevron-left"></i> 链路追踪zipkin
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/08/01/%E5%AF%B9%E8%B1%A1%E6%B1%A0%E5%AE%9E%E6%88%98-%E7%BC%96%E5%86%99%E4%B8%80%E4%B8%AA%E6%95%B0%E6%8D%AE%E5%BA%93%E8%BF%9E%E6%8E%A5%E6%B1%A0/" rel="next" title="对象池实战-编写一个数据库连接池">
                  对象池实战-编写一个数据库连接池 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>







<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">一年春又来</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/local-search.js"></script>






  





</body>
</html>
